#!/bin/bash

#############################################################
# 前端项目Docker镜像构建与发布脚本
#############################################################
# 
# 功能说明:
#   1. 使用Dockerfile构建前端项目Docker镜像
#   2. 推送镜像到Docker仓库
#   3. 支持参数记忆功能
#
# 参数选项:
#   -P: 自动推送镜像到Docker仓库
#   -E: 从环境变量读取所有配置信息，而非交互式输入
#   -C: 构建完成后清理本地Docker镜像
#
# 环境变量:
#   基本环境变量:
#   IMAGE_NAME: Docker镜像名称 (默认: "rbac-admin-frontend")
#   IMAGE_TAG: Docker镜像标签 (默认: 当前时间戳)
#
#   当使用 -E 参数时需要设置:
#   DOCKER_REGISTRY: Docker仓库地址
#   DOCKER_USERNAME: Docker仓库账号
#   DOCKER_PASSWORD: Docker仓库密码
#
# 使用示例:
#   1. 构建Docker镜像，交互式输入:
#      ./build.sh
#
#   2. 构建镜像，并推送到Docker仓库:
#      ./build.sh -P
#
#   3. 使用环境变量自动化构建并推送:
#      export IMAGE_NAME="my-custom-image"
#      export DOCKER_REGISTRY="registry.example.com"
#      export DOCKER_USERNAME="username"
#      export DOCKER_PASSWORD="password"
#      ./build.sh -P -E
#
#   4. 构建后清理本地镜像:
#      ./build.sh -C
#
#############################################################

# 解析命令行参数
PUSH_IMAGE=false
USE_ENV_VARS=false
CLEAN_IMAGES=false

while getopts "PEC" opt; do
  case $opt in
    P)
      PUSH_IMAGE=true
      ;;
    E)
      USE_ENV_VARS=true
      ;;
    C)
      CLEAN_IMAGES=true
      ;;
    \?)
      echo "无效参数: -$OPTARG" >&2
      exit 1
      ;;
  esac
done

# 设置变量
DEFAULT_IMAGE_NAME="rbac-admin-frontend"
DEFAULT_IMAGE_TAG=$(date +"%Y%m%d%H%M")
LATEST_TAG="latest"
PARAMS_FILE="$(dirname "$0")/.build_params"

# 参数记忆功能
load_previous_params() {
  if [ -f "$PARAMS_FILE" ]; then
    echo "发现上次使用的参数:"
    cat "$PARAMS_FILE"
    echo -n "是否使用上次的参数? (y/n): "
    read -r use_previous
    if [[ "$use_previous" =~ ^[Yy]$ ]]; then
      # 加载上次的参数
      source "$PARAMS_FILE"
      echo "已加载上次参数"
      return 0
    fi
  fi
  return 1
}

save_params() {
  # 保存当前参数到文件
  echo "IMAGE_NAME=\"$IMAGE_NAME\"" > "$PARAMS_FILE"
  echo "IMAGE_TAG=\"$IMAGE_TAG\"" >> "$PARAMS_FILE"
  if [ "$PUSH_IMAGE" = true ]; then
    echo "DOCKER_REGISTRY=\"$DOCKER_REGISTRY\"" >> "$PARAMS_FILE"
    echo "DOCKER_USERNAME=\"$DOCKER_USERNAME\"" >> "$PARAMS_FILE"
    # 不保存密码到文件，出于安全考虑
  fi
}

# 根据是否使用环境变量来设置配置
if [ "$USE_ENV_VARS" = true ]; then
  # 使用环境变量
  
  # 检查必要的环境变量
  if [ "$PUSH_IMAGE" = true ]; then
    if [ -z "$DOCKER_REGISTRY" ]; then
      echo "错误: 使用 -E 参数时，环境变量 DOCKER_REGISTRY 必须设置"
      exit 1
    fi
    
    if [ -z "$DOCKER_USERNAME" ] || [ -z "$DOCKER_PASSWORD" ]; then
      echo "错误: 使用 -E 参数时，环境变量 DOCKER_USERNAME 和 DOCKER_PASSWORD 必须设置"
      exit 1
    fi
  fi
  
  # 设置镜像名称
  IMAGE_NAME=${IMAGE_NAME:-$DEFAULT_IMAGE_NAME}
  
  # 设置镜像标签
  IMAGE_TAG=${IMAGE_TAG:-$DEFAULT_IMAGE_TAG}
  
else
  # 尝试加载上次参数
  if ! load_previous_params; then
    # 交互式输入
    echo "====================================================="
    echo "  Docker镜像构建与发布脚本 - 配置"
    echo "====================================================="

    # 镜像名称
    echo -n "请输入镜像名称: "
    read -r input_name
    IMAGE_NAME=${input_name:-$DEFAULT_IMAGE_NAME}
    
    # 镜像标签
    echo -n "请输入镜像标签 [${DEFAULT_IMAGE_TAG}]: "
    read -r input_tag
    IMAGE_TAG=${input_tag:-$DEFAULT_IMAGE_TAG}
    
    # 如果需要推送镜像，获取Docker仓库信息
    if [ "$PUSH_IMAGE" = true ]; then
      echo -n "请输入Docker仓库地址: "
      read -r DOCKER_REGISTRY
      while [ -z "$DOCKER_REGISTRY" ]; do
        echo "Docker仓库地址不能为空，请重新输入:"
        read -r DOCKER_REGISTRY
      done
      
      echo -n "请输入Docker仓库用户名: "
      read -r DOCKER_USERNAME
      while [ -z "$DOCKER_USERNAME" ]; do
        echo "Docker仓库用户名不能为空，请重新输入:"
        read -r DOCKER_USERNAME
      done
      
      echo -n "请输入Docker仓库密码: "
      read -rs DOCKER_PASSWORD
      echo
      while [ -z "$DOCKER_PASSWORD" ]; do
        echo "Docker仓库密码不能为空，请重新输入:"
        read -rs DOCKER_PASSWORD
        echo
      done
    fi
    
    # 保存参数以供下次使用
    save_params
  fi
fi

# 输出脚本信息
echo "====================================================="
echo "  Docker镜像构建与发布脚本"
echo "====================================================="
echo "镜像名称: ${IMAGE_NAME}:${IMAGE_TAG}"
if [ "$PUSH_IMAGE" = true ]; then
  echo "Docker仓库: ${DOCKER_REGISTRY}"
fi
echo "====================================================="
echo "推送镜像: ${PUSH_IMAGE}"
echo "使用环境变量: ${USE_ENV_VARS}"
echo "清理镜像: ${CLEAN_IMAGES}"
echo "====================================================="

# 进入项目根目录
cd "$(dirname "$0")/../" || exit 1

# 检查Dockerfile是否存在
if [ ! -f "Dockerfile" ]; then
  echo "错误: 未找到Dockerfile"
  echo "请确保Dockerfile存在于项目根目录"
  exit 1
fi

# 构建Docker镜像
echo "[1/2] 构建Docker镜像..."
docker build -t ${IMAGE_NAME}:${IMAGE_TAG} -t ${IMAGE_NAME}:${LATEST_TAG} -f Dockerfile .

# 检查构建结果
if [ $? -ne 0 ]; then
  echo "Docker镜像构建失败，退出脚本"
  exit 1
fi

echo "Docker镜像构建成功"
echo "镜像信息:"
docker images | grep ${IMAGE_NAME}

# 推送镜像逻辑
if [ "$PUSH_IMAGE" = true ]; then
  echo "[2/2] 准备推送Docker镜像..."
  
  # 登录Docker仓库
  echo "正在登录Docker Registry..."
  echo "$DOCKER_PASSWORD" | docker login ${DOCKER_REGISTRY} -u "$DOCKER_USERNAME" --password-stdin
  
  if [ $? -ne 0 ]; then
    echo "Docker Registry登录失败，退出脚本"
    exit 1
  fi
  
  # 标记镜像（如果需要）
  if [ -n "$DOCKER_REGISTRY" ]; then
    REGISTRY_IMAGE_NAME="${DOCKER_REGISTRY}/${IMAGE_NAME}"
    echo "标记镜像: ${REGISTRY_IMAGE_NAME}:${IMAGE_TAG}"
    docker tag "${IMAGE_NAME}:${IMAGE_TAG}" "${REGISTRY_IMAGE_NAME}:${IMAGE_TAG}"
    docker tag "${IMAGE_NAME}:${LATEST_TAG}" "${REGISTRY_IMAGE_NAME}:${LATEST_TAG}"
    
    # 推送镜像
    echo "推送镜像到Docker仓库 ${DOCKER_REGISTRY}..."
    docker push "${REGISTRY_IMAGE_NAME}:${IMAGE_TAG}"
    docker push "${REGISTRY_IMAGE_NAME}:${LATEST_TAG}"
  else
    # 推送镜像
    echo "推送镜像..."
    docker push "${IMAGE_NAME}:${IMAGE_TAG}"
    docker push "${IMAGE_NAME}:${LATEST_TAG}"
  fi
  
  echo "镜像推送完成"
else
  echo "[2/2] 跳过镜像推送"
fi

echo "====================================================="
echo "构建和发布流程已完成!"
echo "镜像地址: ${IMAGE_NAME}:${IMAGE_TAG}"
echo "镜像地址: ${IMAGE_NAME}:${LATEST_TAG}"
if [ "$PUSH_IMAGE" = true ] && [ -n "$DOCKER_REGISTRY" ]; then
  echo "远程镜像: ${REGISTRY_IMAGE_NAME}:${IMAGE_TAG}"
  echo "远程镜像: ${REGISTRY_IMAGE_NAME}:${LATEST_TAG}"
fi
echo "====================================================="

# 清理本地镜像（如果启用）
if [ "$CLEAN_IMAGES" = true ]; then
  echo "清理本地Docker镜像..."
  docker rmi ${IMAGE_NAME}:${IMAGE_TAG}
  docker rmi ${IMAGE_NAME}:${LATEST_TAG}
  if [ "$PUSH_IMAGE" = true ] && [ -n "$DOCKER_REGISTRY" ]; then
    docker rmi ${REGISTRY_IMAGE_NAME}:${IMAGE_TAG}
    docker rmi ${REGISTRY_IMAGE_NAME}:${LATEST_TAG}
  fi
  echo "本地镜像清理完成"
fi

# 使用说明
echo "===== 使用说明 ====="
echo "运行容器示例:"
echo "docker run --rm -p 80:80 -e BACKEND_API_URL=http://127.0.0.1:8080/api ${IMAGE_NAME}:${IMAGE_TAG}"
echo "====================================================="
